/*
* 施工作业许可详情
* */
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/enums.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_radio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'package:images_picker/images_picker.dart';
import 'package:http_parser/http_parser.dart';

class WorkPermitDetail extends StatefulWidget {
  const WorkPermitDetail();

  @override
  _WorkPermitDetailState createState() => _WorkPermitDetailState();
}

class _WorkPermitDetailState extends State<WorkPermitDetail> {
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  var ids = Go.Get.arguments;
  var detail = Map();
  List workList = []; //作业条件

  List signPerson = [];

  List typeList = ['1', '2', '3', '4', '5'];
  List typeList2 = ['6','7','8'];
  List<Media> photos = [];
  ImageForm.FormData formData;
  List passPhoto = [];

  var startTime = '';
  var endTime = '';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getDetail();
    this.getPerson();
  }

  /*
  * 获取详情
  * */
  getDetail() async {
    var result = await getConsWorkLicenseEx({
      'id': ids['businessId'],
    });
    if (result != null && result.length > 0) {
      this.setState(() {
        detail = result;
        workList = detail['workLicenseResults'];
        startTime = result['planWorkTimeStr'];
        endTime = Utils.timeUtil(DateTime.parse(result['planWorkTimeStr']).add(Duration(days: 30)).toIso8601String());
      });
    }
  }

  /*
  * 获取作业条件确认、复核人员
  * */
  getPerson() async {
    var result = await getSignTypeCodeDef({
      'projectSectionId': GlobalConfig.selectFactory.tag,
    });
    if (result != null && result.length > 0) {
      List tem = [];
      result.forEach((element) {
        if (this.getTaskType().contains(element['signType']) &&
            element['userId'] == GlobalConfig.userInfo['userId']) {
          tem.add(element);
        }
      });
      this.setState(() {
        signPerson = tem;
      });
    }
  }

  List getTaskType(){
    switch (ids['taskKey']){
      case 'license_confirm':
        return typeList;
        break;
      case 'license_check':
        return typeList2;
        break;
      default:
        return ['9'];

    }
  }

  Future addImage() async {
    this.passPhoto = [];
    loading.show(delay: 30);
    var tem = [];
    for (var l = 0; l < signPerson.length; l++) {
      if (signPerson[l]['paint'] != null) {
        tem.add(l);
        passPhoto.add(signPerson[l]);
      }
    }
    if (this.passPhoto.length > 0) {
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < passPhoto.length; i++) {
        formData.files.add(MapEntry(
            "files",
            await ImageForm.MultipartFile.fromBytes(passPhoto[i]['paint'],
                filename: "bbq.jpg", contentType: MediaType('image', 'png'))));
      }
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        for (var i = 0; i < result.length; i++) {
          signPerson[i]['signId'] = result[i]['attachmentId'];
        }
      }
    }
    this.submit();
  }

  submit() async {
    var pass = {
      'workLicenseId': ids['businessId'],
      'workLicenseSigns':jsonEncode(signPerson.map((e) => {
        'signType':e['signType'],
        'signResult':e['selectType']!=null?e['selectType'].value:'1',
        'signId':e['signId'],
        'signTime':Utils.timeUtil(DateTime.now().toIso8601String()),
      }).toList()),
      'taskId':ids['taskId'],
      'taskKey':ids['taskKey']
    };
    if(ids['taskKey']!=null&&ids['taskKey']=='license_end'){
      pass['startTime'] = startTime;
      pass['endTime'] = endTime;
    }
    var result = await saveConsWorkLicenseProcess(pass);
    loading.dismiss();
    if (result != null) {
      Fluttertoast.showToast(msg: '审批成功');
      Go.Get.back(result: '成功');
      bus.emit('refreshHome');
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('作业许可'),
      ),
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).padding.bottom + 40),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  padding:
                  EdgeInsets.fromLTRB(Styles.spacing4, 0, Styles.spacing4, 0),
                  color: Colors.white,
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing16, Styles.spacing8, Styles.spacing16),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '基本信息',
                          style: TextStyle(
                              color: Styles.BlackColor,
                              fontSize: Styles.MainButtonTextFont,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                      Container(
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    color: Styles.LightSearch, width: 1))),
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing16, Styles.spacing8, Styles.spacing16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '工程名称',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            ),
                            Text(
                              detail['projectName'] ?? '--',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            )
                          ],
                        ),
                      ),
                      Container(
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    color: Styles.LightSearch, width: 1))),
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing16, Styles.spacing8, Styles.spacing16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '分部分项工程名称',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            ),
                            Text(
                              detail['partProjectName'] ?? '--',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            )
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing16, Styles.spacing8, Styles.spacing4),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '施工内容',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    color: Styles.LightSearch, width: 1))),
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing4, Styles.spacing8, Styles.spacing16),
                        child: Text(
                          detail['workContent'] ?? '--',
                          style: TextStyle(
                              color: Styles.TitleColor,
                              fontSize: Styles.Middle15Font),
                        ),
                      ),
                      Container(
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    color: Styles.LightSearch, width: 1))),
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing16, Styles.spacing8, Styles.spacing16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '申请人',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            ),
                            (detail['workLicenseSigns'] != null &&
                                detail['workLicenseSigns'].length > 0)
                                ? Image.network(
                              "${GlobalConfig.baseUrl}fs/irest/file/mps_fileTransferHandler/image?id=${detail['workLicenseSigns'][0]['signId']}&ZJQFSESSION=${GlobalConfig.session}",
                              width: 80.w,
                              height: 26.h,
                            )
                                : Container()
                          ],
                        ),
                      ),
                      Container(
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    color: Styles.LightSearch, width: 1))),
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing16, Styles.spacing8, Styles.spacing16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '申请时间',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            ),
                            Text(
                              detail['applyTimeStr'] ?? '--',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            )
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing16, Styles.spacing8, Styles.spacing16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '计划施工时间',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            ),
                            Text(
                              detail['planWorkTimeStr'] ?? '--',
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.only(top: Styles.spacing16),
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.fromLTRB(Styles.spacing16,
                            Styles.spacing16, Styles.spacing8, Styles.spacing16),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '作业条件确认',
                          style: TextStyle(
                              color: Styles.BlackColor,
                              fontSize: Styles.MainButtonTextFont,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                      ListView.builder(
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: workList.length,
                        itemBuilder: (BuildContext context, int index) {
                          //条目构建函数传入了index,根据index索引到特定图片
                          return Container(
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(
                                        color: Styles.SpatLineColor, width: 1))),
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing16,
                                Styles.spacing16,
                                Styles.spacing16,
                                Styles.spacing16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text.rich(TextSpan(children: [
                                  TextSpan(
                                      text: "${(index + 1).toString()}、",
                                      style: TextStyle(
                                          color: Styles.TitleColor,
                                          fontSize: Styles.Middle15Font)),
                                  TextSpan(
                                      text:
                                      workList[index]['checkContent'] ?? '--',
                                      style: TextStyle(
                                          color: Styles.TitleColor,
                                          fontSize: Styles.Middle15Font)),
                                  WidgetSpan(
                                      child: SizedBox(
                                        child: Text(
                                          "[${workList[index]['checkResult'] ?? '合格'}]",
                                          style: TextStyle(
                                              color: Styles.BlueColor,
                                              fontSize: Styles.Middle15Font),
                                        ),
                                      )),
                                ])),
                              ],
                            ),
                          );
                        },
                      ),

                    ],
                  ),
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.only(top: Styles.spacing16),
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.fromLTRB(Styles.spacing16,
                            Styles.spacing16, Styles.spacing8, Styles.spacing16),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '确认签字',
                          style: TextStyle(
                              color: Styles.BlackColor,
                              fontSize: Styles.MainButtonTextFont,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                      ListView.builder(
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: signPerson.length,
                        itemBuilder: (BuildContext context, int index) {
                          //条目构建函数传入了index,根据index索引到特定图片
                          return Container(
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(
                                        color: Styles.SpatLineColor,
                                        width: 1))),
                            padding: EdgeInsets.fromLTRB(Styles.spacing16,
                                Styles.spacing16, Styles.spacing16, 0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  margin: EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing16,
                                      Styles.spacing16, Styles.spacing16),
                                  alignment: Alignment.centerLeft,
                                  color: Colors.white,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text.rich(TextSpan(children: [
                                        TextSpan(
                                            text: PersonType.getPersonTypeStr2(
                                                signPerson[index]['signType']),
                                            style: TextStyle(
                                                fontSize: Styles.Middle15Font,
                                                color: Styles.TitleColor)),
                                      ])),
                                      GestureDetector(
                                        onTap: () async {
                                          print('签名');
                                          var result =
                                          await Go.Get.toNamed(RouteConfig.sign);
                                          if (result != null) {
                                            signPerson[index]['paint'] = result;
                                          }
                                          this.setState(() {});
                                        },
                                        child: Container(
                                          child: signPerson[index]['paint'] != null
                                              ? Image.memory(
                                            signPerson[index]['paint'],
                                            width: 80.w,
                                            height: 30.h,
                                          )
                                              : Icon(
                                            Icons.mode_edit,
                                            color: Styles.BlueColor,
                                            size: Styles.MiddleFont17,
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                Container(
                                  alignment: Alignment.centerLeft,
                                  color: Colors.white,
                                  child: CustomRadio(
                                    currentItem:
                                    signPerson[index]['selectType'] != null
                                        ? signPerson[index]['selectType']
                                        : SelectItems(
                                        label: '同意', value: '1'),
                                    top: 0,
                                    selectList: [
                                      SelectItems(label: '同意', value: '1'),
                                      SelectItems(label: '不同意', value: '0')
                                    ],
                                    selectCallback: (item) {
                                      this.setState(() {
                                        signPerson[index]['selectType'] = item;
                                      });
                                    },
                                    title: '',
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),

                    ],
                  ),
                ),
                ids['taskKey']=='license_end'?Column(
                  children: [
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(Styles.spacing16,
                          Styles.spacing16, Styles.spacing8, Styles.spacing16),
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '许可证有效期',
                        style: TextStyle(
                            color: Styles.BlackColor,
                            fontSize: Styles.MainButtonTextFont,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                    Container(
                      decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border(
                              bottom: BorderSide(
                                  color: Styles.LightSearch, width: 1))),
                      padding: EdgeInsets.fromLTRB(Styles.spacing16,
                          Styles.spacing16, Styles.spacing16, Styles.spacing16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '许可证有效期',
                            style: TextStyle(
                                color: Styles.TitleColor,
                                fontSize: Styles.Middle15Font),
                          ),
                          GestureDetector(
                            onTap: (){
                              String format = 'yyyy-MM-dd';
                              BrnPickerTitleConfig pickerTitleConfig = BrnPickerTitleConfig(titleContent: "选择时间范围");
                              BrnDateRangePicker.showDatePicker(context,
                                  isDismissible: false,
                                  minDateTime: DateTime(2010, 06, 01, 00, 00, 00),
                                  maxDateTime: DateTime(2029, 07, 24, 23, 59, 59),
                                  pickerMode: BrnDateTimeRangePickerMode.date,
                                  minuteDivider: 10,
                                  pickerTitleConfig: pickerTitleConfig,
                                  dateFormat: format,
                                  initialStartDateTime: DateTime.parse(startTime),
                                  initialEndDateTime: DateTime.parse(endTime),
                                  onConfirm: (startDateTime, endDateTime, startlist, endlist) {
                                    this.setState(() {
                                      startTime = Utils.timeUtil(startDateTime.toIso8601String());
                                      endTime = Utils.timeUtil(endDateTime.toIso8601String());
                                    });
                                  }, onClose: () {
                                    print("onClose");
                                  }, onCancel: () {
                                    print("onCancel");
                                  }, onChange: (startDateTime, endDateTime, startlist, endlist) {
                                    BrnToast.show(
                                        "onChange:  $startDateTime   $endDateTime     $startlist     $endlist", context);
                                  });
                            },
                            child: Text(
                              "$startTime至$endTime",
                              style: TextStyle(
                                  color: Styles.TitleColor,
                                  fontSize: Styles.Middle15Font),
                            ),
                          )

                        ],
                      ),
                    ),
                  ],
                ):Container()
              ],
            ),
          ),
        ),
      ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                showDialog(
                    barrierDismissible: false,
                    context: this.context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('注意'),
                        content: Text('确认提交吗？'),
                        actions: <Widget>[
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "取消",
                                style: TextStyle(color: Colors.black),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ),
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "确定",
                                style: TextStyle(color: Colors.red),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                                this.addImage();
                                // this.submit();
                              },
                            ),
                          ),
                        ],
                      );
                    });
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确定提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        )
    );
  }
}
